package com.ecoolex.hotel.saas.core.manager;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.hotel.saas.core.dao.StoreAdPositionDAO;
import com.ecoolex.hotel.saas.entity.StoreAd;
import com.ecoolex.hotel.saas.entity.StoreAdPosition;
import com.ecoolex.hotel.saas.entity.StoreAdPosition.Column;
import com.ecoolex.hotel.saas.entity.StoreAdPositionExample;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StoreAdPositionManager {
	
    @Autowired
    private StoreAdPositionDAO dao;
    
    void updatePositionByAd(StoreAd ad, List<StoreAdPosition> positionList, String createUser) {
        // 删除所有
        StoreAdPositionExample example = new StoreAdPositionExample();
        example.createCriteria().andAdIdEqualTo(ad.getAdId()).andDeletedEqualTo(StoreAdPosition.NOT_DELETED);
        dao.deleteByExample(example);

        positionList.forEach(position -> {
            // 验证
            BizAssert.isTrue(Check.notNullOrTrimEmpty(position.getPosition()), ResultCode.VERIFY.build(201), "位置信息为空");

            position.setAdId(ad.getAdId());
            position.setDeleted(StoreAdPosition.NOT_DELETED);
            position.setUpdateUser(createUser);
            position.setUpdateTime(Date.from(Instant.now()));
            position.setCreateUser(createUser);
            position.setCreateTime(Date.from(Instant.now()));
            dao.insert(position);
        });
    }

    void deleteByAdId(int adId) {
        StoreAdPositionExample example = new StoreAdPositionExample();
        example.createCriteria().andAdIdEqualTo(adId).andDeletedEqualTo(StoreAdPosition.NOT_DELETED);

        StoreAdPosition record = new StoreAdPosition();
        record.setDeleted(StoreAdPosition.IS_DELETED);
        // 变更delete字段
        dao.updateByExampleSelective(record, example, Column.deleted);
    }

    public List<StoreAdPosition> queryByAdId(int adId) {
        StoreAdPositionExample example = new StoreAdPositionExample();
        example.createCriteria().andAdIdEqualTo(adId).andDeletedEqualTo(StoreAdPosition.NOT_DELETED);
        return dao.selectByExample(example);
    }
}